package com.Java.train.business.service.Impl;

import com.Java.train.common.response.CommonResp;
import com.Java.train.business.entity.DTO.TrainStationDTO;
import com.Java.train.business.req.TrainStationQueryReq;
import com.Java.train.common.exception.BusniessException;
import com.Java.train.common.exception.BusniessExceptionEnum;
import com.Java.train.common.response.PageResp;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.Java.train.business.entity.TrainStation;
import com.Java.train.business.mapper.TrainStationMapper;
import com.Java.train.business.service.TrainStationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.Java.train.common.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.date.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
/**
* 火车车站 服务实现类
*
* @author luomoxingchen
* @since 2024-09-22
*/
@Service
public class TrainStationServiceImpl extends ServiceImpl<TrainStationMapper, TrainStation> implements TrainStationService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainStationService.class);

    @Autowired
    TrainStationMapper trainStationMapper;


    @Override
    public PageResp<TrainStationDTO> queryList(TrainStationQueryReq trainStationQueryReq){
        // 1.获取当前用户id信息
        //        Long id = LoginMemberContext.getId();
        String trainCode = trainStationQueryReq.getTrainCode();
        // 2.查询数据库中是否存在当前信息（id）
        LOG.info("查询页码：{}", trainStationQueryReq.getPage());
        LOG.info("每页条数：{}", trainStationQueryReq.getSize());
        PageHelper.startPage(trainStationQueryReq.getPage(),trainStationQueryReq.getSize());
        // 条件查询
        List<TrainStation> trainStations = null;
        if(StrUtil.isNotBlank(trainCode)){
            LambdaQueryWrapper<TrainStation> wrapper = new LambdaQueryWrapper<>();
            List<TrainStation> list = list(wrapper.eq(TrainStation::getTrainCode, trainCode));
        }else {
            trainStations = list();
        }

        if(trainStations == null || CollUtil.isEmpty(trainStations)){
            // 返回空列表
            return new PageResp<TrainStationDTO>();
//            throw new BusniessException(BusniessExceptionEnum.MEMBER_PASSENGER_NOT_EXITS);
        }

        // 3 分析分页信息
        // 3.1 获取分页总条数和页数
        PageInfo<TrainStation> pageInfo = new PageInfo<>(trainStations);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // 3.2 转为封装后的返回值并封装到分页返回值中
        List<TrainStationDTO> list = BeanUtil.copyToList(trainStations, TrainStationDTO.class);
        PageResp<TrainStationDTO> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        // 4.返回查询到的信息
        return pageResp;
    }

    @Override
    public CommonResp<Object> modify(TrainStation trainStation) {
        Long id = trainStation.getId();
        DateTime dateTime = DateTime.now();
        if(ObjectUtil.isNull(id)){
            // 查重
            // 查idx和traincode
            TrainStation trainStationDB = getTrainStationByTrainCodeAndIdx(trainStation.getTrainCode(), trainStation.getIdx());
            if(ObjectUtil.isNotEmpty(trainStationDB)){
                throw new BusniessException(BusniessExceptionEnum.BUSINESS_TRAINSTATION_ALREADY_EXITS);
            }

            // 查name和traincode
            TrainStation trainStationDB1 = getTrainStationByTrainCodeAndName(trainStation.getTrainCode(), trainStation.getName());
            if(ObjectUtil.isNotEmpty(trainStationDB1)){
                throw new BusniessException(BusniessExceptionEnum.BUSINESS_TRAINSTATION_ALREADY_EXITS);
            }

            trainStation.setId(SnowFlakeUtil.getSnowFlakeNextId());
            trainStation.setCreateTime(dateTime);
            trainStation.setUpdateTime(dateTime);
            boolean save = save(trainStation);
            return new CommonResp<>(save);
        } else {
            trainStation.setUpdateTime(dateTime);
            boolean update = updateById(trainStation);
            return new CommonResp<>(update);
        }
    }

    @Override
    public CommonResp<Object> remove(String ids) {
        if(StrUtil.isNotEmpty(ids)){
            String[] array = ids.split(",");
            if(!CollectionUtils.isEmpty(Arrays.asList(array))) {
                return new CommonResp<>(trainStationMapper.deleteBatchIds(Arrays.asList(array)));
            }
        }
        return new CommonResp<>(Collections.EMPTY_LIST);
    }

    // 通过唯一键校验查重
    private TrainStation getTrainStationByTrainCodeAndIdx(String trainCode, Integer idx) {
        LambdaQueryWrapper<TrainStation> wrapper = new LambdaQueryWrapper<>();
        TrainStation one = getOne(wrapper.eq(TrainStation::getTrainCode, trainCode).eq(TrainStation::getIdx, idx));
        return one;
    }
    private TrainStation getTrainStationByTrainCodeAndName(String trainCode, String name) {
        LambdaQueryWrapper<TrainStation> wrapper = new LambdaQueryWrapper<>();
        TrainStation one = getOne(wrapper.eq(TrainStation::getTrainCode, trainCode).eq(TrainStation::getName, name));
        return one;
    }

}


